package com.leyou.auth.config;

import com.leyou.auth.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @Author: Rose
 * @Date: 2021/4/10 16:05
 * @description ${description}
 * @version: 1.0.0
 */
@Data
@ConfigurationProperties(prefix = "ly.wt")
public class JwtProperties {

    /**
     * 密钥
     */
    private String secret;

    /**
     * 公钥
     */
    private String pubkeyPath;

    /**
     * 私钥
     */
    private String prikeyPath;


    /**
     * tokenName
     */
    private String cookieName;

    /**
     * 过期时间
     */
    private int expire;

    private PublicKey pubKey;

    private PrivateKey priKey;

    // 类一旦加载, 就应该读取公钥和私钥
    // 加载时机: 对象一旦实例化后,就应该读取公钥和私钥
    @PostConstruct // 构造函数初始化完毕之后,调用此方法
    public void init() throws Exception {
        // 公钥和私钥如果不存在,先生成
        File pubPath = new File(pubkeyPath);
        File priPath = new File(prikeyPath);
        if (!pubPath.exists() || !priPath.exists()) {
            // 生成私钥和公钥
            RsaUtils.generateKey(pubkeyPath, prikeyPath, secret, 1024);
        }
        // 读取公钥和私钥
        this.pubKey = RsaUtils.getPublicKey(pubkeyPath);
        this.priKey = RsaUtils.getPrivateKey(prikeyPath);

    }
}
